--
-- Created by IntelliJ IDEA.
-- User: lblue
-- Date: 11/24/19
-- Time: 9:46 PM
-- 八皇后问题

--棋盘大小
N = 8
isFind = false
-- 检查(n, c)是否会被攻击
function isPlaceOK(a, n, c)
    for i = 1, n - 1 do
        --  是否在同一列、同一右对角线、同一左对角线
        if (a[i] == c) or (a[i]-i == c-n ) or (a[i]+i == c+n ) then
            return false
        end
    end
    return true
end

-- 打印棋盘
function printSolution(a)
    for i=1, N do
        for j=1, N do
            -- print x or -
            io.write(a[i] == j and "X" or "-", " ")
        end
        io.write("\n")
    end
    io.write("\n")
    isFind = true
end


-- 把 n 到 N 的所有皇后放在棋盘上
function addQueen(a, n)
    if n > N then
        printSolution(a)
    else
        for c=1, N do
            if isPlaceOK(a, n, c) and not isFind then
                a[n] = c
                addQueen(a, n+1)
            end
        end
    end
end

-- run
addQueen({}, 1)
